package com.zlsy.thread.flowcontrol.countdownlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @author zhouliang
 * @date 2020/9/2 14:38
 * 例子：工厂中质检，5个工人检查，所以人都检查通过，产品才合格；
 */
public class CountDownLatchDemo1 implements Runnable {

    private CountDownLatch latch;

    public CountDownLatchDemo1(CountDownLatch latch) {
        this.latch = latch;
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
        CountDownLatchDemo1 r = new CountDownLatchDemo1(latch);
        for (int i = 0; i < 5; i++) {
            final Thread t = new Thread(r, "质检员" + (i + 1) + "号");
            t.start();
        }

        latch.await();

        System.out.println("质检通过！");
    }

    @Override
    public void run() {
        try {
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(Thread.currentThread().getName() + "检查完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    }
}
